﻿//-----------------------------------------------------------------------
// <copyright file="InstallController.cs" company="OOHM PROCESSAMENTO DE DADOS LTDA.">
//     Microsoft Public License (MS-PL) This license governs use of the accompanying
//     software. If you use the software, you accept this license. If you do not
//     accept the license, do not use the software. 1. Definitions The terms "reproduce,"
//     "reproduction," "derivative works," and "distribution" have the same meaning
//     here as under U.S. copyright law. A "contribution" is the original software,
//     or any additions or changes to the software. A "contributor" is any person
//     that distributes its contribution under this license. "Licensed patents"
//     are a contributor's patent claims that read directly on its contribution.
//     2. Grant of Rights (A) Copyright Grant- Subject to the terms of this license,
//     including the license conditions and limitations in section 3, each contributor
//     grants you a non-exclusive, worldwide, royalty-free copyright license to
//     reproduce its contribution, prepare derivative works of its contribution,
//     and distribute its contribution or any derivative works that you create.
//     (B) Patent Grant- Subject to the terms of this license, including the license
//     conditions and limitations in section 3, each contributor grants you a non-exclusive,
//     worldwide, royalty-free license under its licensed patents to make, have
//     made, use, sell, offer for sale, import, and/or otherwise dispose of its
//     contribution in the software or derivative works of the contribution in
//     the software. 3. Conditions and Limitations (A) No Trademark License- This
//     license does not grant you rights to use any contributors' name, logo, or
//     trademarks. (B) If you bring a patent claim against any contributor over
//     patents that you claim are infringed by the software, your patent license
//     from such contributor to the software ends automatically. (C) If you distribute
//     any portion of the software, you must retain all copyright, patent, trademark,
//     and attribution notices that are present in the software. (D) If you distribute
//     any portion of the software in source code form, you may do so only under
//     this license by including a complete copy of this license with your distribution.
//     If you distribute any portion of the software in compiled or object code
//     form, you may only do so under a license that complies with this license.
//     (E) The software is licensed "as-is." You bear the risk of using it. The
//     contributors give no express warranties, guarantees or conditions. You may
//     have additional consumer rights under your local laws which this license
//     cannot change. To the extent permitted under your local laws, the contributors
//     exclude the implied warranties of merchantability, fitness for a particular
// </copyright>
//-----------------------------------------------------------------------
namespace AbstractSaaSTemplate.UI.Web.Controllers{    using System;
    using System.Web.Mvc;
    using AbstractSaaSTemplate.Application.Configuration;
    using AbstractSaaSTemplate.Application.Framework;
    using AbstractSaaSTemplate.Application.Mvc;
    using AbstractSaaSTemplate.Domain.Models.Enumerators;
    using AbstractSaaSTemplate.Domain.Services;
    using AbstractSaaSTemplate.UI.Web.Models.Install;
    using OOHM.Framework.Configuration;

    /// <summary>
    /// Provides HTTP processing logic for the conceptual entity 'Install'
    /// in the '/Setup' module of the application.
    /// </summary>
    public sealed class InstallController : ApplicationController
    {
        #region Session Keys

        /// <summary>
        /// Keeps the session key for 'SetupStep1Form'
        /// </summary>
        private const string SetupStep1FormKey = "SetupStep1Form";

        /// <summary>
        /// Keeps the session key for 'SetupStep2Form'
        /// </summary>
        private const string SetupStep2FormKey = "SetupStep2Form";

        /// <summary>
        /// Keeps the session key for 'SetupStep3Form'
        /// </summary>
        private const string SetupStep3FormKey = "SetupStep3Form";

        #endregion

        /// <summary>
        /// Initializes a new instance of the InstallController class
        /// injecting the services and repositories required for operation.
        /// </summary>
        /// <param name="serviceForSetup">The repository to operate the setup.</param>
        public InstallController(ISetupService serviceForSetup)
        {
            this.ServiceForSetup = serviceForSetup;
        }

        /// <summary>
        /// Gets the service to consume 'Setup' services.
        /// </summary>
        public ISetupService ServiceForSetup { get; private set; }
    
        /// <summary>
        /// GET: /Install/
        /// Provides a landing page for the 'Install' section of the area.
        /// </summary>
        /// <returns>Returns a view containing a landing page</returns>
        public ActionResult Index()
        {
            var installed = Configurator.GetConfigurationByKey<bool>(ConfigurationKeys.Installed);
            this.ViewBag.Installed = installed;
            return this.Result();
        }

        /// <summary>
        /// POST: /Setup/Install/Step1
        /// Processes the user input and try to proceed with the step 1 of the installation.
        /// </summary>
        /// <param name="input">The user input parsed into the form class.</param>
        /// <returns>Retrieves a JsonResult with an object containing the property "Result".</returns>
        public ActionResult Step1(Step1Form input)
        {
        // we check the basic input and prevents null values for it
        if (input == null)
        {
            throw new ArgumentNullException("input");
        }

        // we reinforce the model validation
        // this will ensure that the validation is performed
        // even when we are invoking this method from a unit test instead
        // of a HttpRequest.
        if (this.ModelState.IsValid)
        {
            this.TryValidateModel(input);
        }

        // once performed the validation we proceed
        // invoking the installation procedures
        // which mimic the basic functions of the system
        if (this.ModelState.IsValid)
        {
            // we save the form state into the session
            // this will be used in the latest step in
            // which all the setup procedure is run
            this.Session[SetupStep1FormKey] = input;
                
            // and we redirect the user to the step 2
            return this.PartialView("Step2");
        }

        return this.Result();
        }

        /// <summary>
        /// POST: /Setup/Install/Step2
        /// Processes the user input and try to proceed with the step 2 of the installation.
        /// </summary>
        /// <param name="input">The user input parsed into the form class.</param>
        /// <returns>Retrieves a JsonResult with an object containing the property "Result".</returns>
        public ActionResult Step2(Step2Form input)
        {
            // we check the basic input and prevents null values for it
            if (input == null)
            {
                throw new ArgumentNullException("input");
            }

            // we reinforce the model validation
            // this will ensure that the validation is performed
            // even when we are invoking this method from a unit test instead
            // of a HttpRequest.
            if (this.ModelState.IsValid)
            {
                this.TryValidateModel(input);
            }

            // once performed the validation we proceed
            // invoking the installation procedures
            // which mimic the basic functions of the system
            if (this.ModelState.IsValid)
            {
                // we save the form state into the session
                // this will be used in the latest step in
                // which all the setup procedure is run
                this.Session[SetupStep2FormKey] = input;

                // we load all forms to dispatch data to the Setup Service.
                var form1 = this.Session[SetupStep1FormKey] as Models.Install.Step1Form;
                var form2 = this.Session[SetupStep2FormKey] as Models.Install.Step2Form;

                // check if all forms are available in the session
                if (form1 == null || form2 == null)
                {
                    return this.PartialView("SetupSessionExpired");
                }

                // we have to parse the string port setup by the
                // installer to the integer which is the port.
                var port = default(int);
                if (!int.TryParse(form2.SmtpPort, out port))
                {
                    port = 25;
                }

                // if all data necessary is available,
                // we proceed with the setup instructions
                var results = this.ServiceForSetup.RunInstall(
                    form1.EncryptionPassphrase,
                    form1.StaffAdminEmailAddress,
                    form1.ConnectionString,
                    form1.BlobsRootPath,
                    form1.BlobsBaseLocation,
                    form2.SmtpHost,
                    port,
                    form2.SmtpLogin,
                    form2.SmtpPassword,
                    form2.SmtpRequiresSsl,
                    form2.EmailDefaultSenderName,
                    form2.EmailDefaultSenderEmailAddress,
                    form2.AppBaseDomain);

                // in case we succeed, we redirect it to the success partial
                if (results.State == SetupInstallationResultState.Success)
                {
                    var passwordGenerated = results.PasswordGenerated;
                    return this.PartialView(
                        "StepSuccess",
                        passwordGenerated);
                }
                else
                {
                    var message = results.State.ToFriendlyMessage();
                    return this.PartialView(
                        "SetupFailed",
                        message);
                }
            }

            return this.Result();
        }
    }
}


